# -*- coding:utf-8 -*-
import sys
from django import forms
from appTest.models import Publisher
from django.core.exceptions import ValidationError

reload(sys)
sys.setdefaultencoding('utf-8')

# 1、表单字段的验证器
# def validate_name(value):
# 	try:
# 		Publisher.objects.get(name=value)
# 		raise ValidationError('{}的信息已经存在'.format(value))
# 	except Publisher.DoesNotExist:
# 		pass


# 2、继承forms.Form定义表单类
# class PublisherForm(forms.Form):
# 	name = forms.CharField(max_length=5,error_messages={'required': 'Please enter your name'})
# 	address = forms.CharField()
# 	city = forms.CharField()
# 	state_province = forms.CharField()
# 	country = forms.CharField()
# 	website = forms.CharField()

# 3、继承forms.ModelForm定义表单类
class PublisherForm(forms.ModelForm):
	# name = forms.CharField(label='名称', validators=[validate_name])

	# 2、clean_filedname验证
	# def clean_name(self): #clean_name为PublisherForm类的方法
	# 	value = self.cleaned_data.get('name')
	# 	try:
	# 		Publisher.objects.get(name=value)
	# 		raise ValidationError('{}的信息已经存在'.format(value))
	# 	except Publisher.DoesNotExist:
	# 		pass
	# 	return value

	# 3、clean验证
	def clean(self):
		cleaned_data = super(PublisherForm,self).clean() #调用父类clean()方法，该方法会返回表单所有数据
		value = cleaned_data.get('name') #指定验证字段数据
		try:
			Publisher.objects.get(name=value)
			self._errors['name']=self.error_class(['{}的信息已存在'.format(value)])
		except Publisher.DoesNotExist:
			pass
		return cleaned_data #没有出错时，返回数据给model调用


	class Meta:
		model = Publisher
		exclude = ('id',)
